package com.library.service.student;

import com.library.dao.*;
import com.library.entity.Libcard;

import java.util.List;

public class BorrowService {
    private BorrowrecDao borrowrecDao = new BorrowrecDao();
    private BookCopyDao bookcopyDao = new BookCopyDao();
    private LibcardDao libcardDao = new LibcardDao();

    // 借书
    public String borrowBooks(String sno, String[] barCodes) {
        if (barCodes == null || barCodes.length == 0) {
            return "请选择要借阅的图书副本！";
        }
        // 1. 检查借书证状态
        Libcard card = libcardDao.getBySno(sno);
        if (card == null) {
            return "无借书证，无法借书！";
        }
        String cardStatus = card.getCardType();
        if (!"正常".equals(cardStatus)) {
            return "借书证状态异常（挂失或注销），无法借书！";
        }
        // 2. 检查未还书本数
        List<Object[]> unreturned = borrowrecDao.getUnreturnedBySno(sno);
        if (unreturned.size() + barCodes.length > 5) {
            return "借书失败：最多只能借5本（含未还），当前未还" + unreturned.size() + "本，最多还能借" + (5-unreturned.size()) + "本！";
        }
        // 3. 检查未缴罚款
        List<Object[]> fineList = borrowrecDao.getFineList(sno, "未缴");
        double totalFine = 0;
        for (Object[] fine : fineList) {
            totalFine += (Double) fine[5];
        }
        if (totalFine > 50) {
            return "借书失败：未缴罚款超过50元，当前未缴罚款：" + totalFine + "元！";
        }
        // 4. 检查副本可借状态并插入借阅记录
        for (String barCode : barCodes) {
            int status = bookcopyDao.getStatusByBarCode(barCode);
            if (status != 1) {
                return "副本条码" + barCode + "不可借！";
            }
        }
        for (String barCode : barCodes) {
            bookcopyDao.updateStatus(barCode, 0);
            borrowrecDao.insertBorrowrec(sno, barCode);
        }
        return "借书成功！共借阅" + barCodes.length + "本书。";
    }

    // 还书
    public String returnBook(String serNum) {
        return borrowrecDao.returnBook(serNum);
    }

    // 查询未归还图书
    public java.util.List<Object[]> getUnreturnedBooks(String sno) {
        return borrowrecDao.getUnreturnedBySno(sno);
    }
} 